<?php
if (is_ajax()) {
    header('Content-Type:application/json; charset=utf-8');

    $action = $_GET['action'];

    if ($action === 'jump') {
        $startPoint = $_GET['start'];
        $endPoint   = $_GET['end'];

        $result = press($startPoint, $endPoint);

        if (0 === $result) {
            usleep(1500000);

            try {
                screen_capture();

                echo json_encode(['status' => 1]);
            } catch (Exception $e) {
                echo json_encode(['status' => 0, 'msg' => $e->getMessage()]);
            }
        } else {
            echo json_encode(['status' => 0]);
        }
    } elseif ($action === 'refresh') {
        try {
            screen_capture();

            echo json_encode(['status' => 1]);
        } catch (Exception $e) {
            echo json_encode(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    exit;
} else {
    header('Content-Type:text/html; charset=utf-8');

    $width  = 1080;
    $height = 1920;
    $url    = $_SERVER['PHP_SELF'];

    try {
        screen_capture();
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

function is_ajax()
{
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'xmlhttprequest' === strtolower($_SERVER['HTTP_X_REQUESTED_WITH']));
}

function screen_capture()
{
    ob_start();

    system('adb shell screencap -p /sdcard/screen.png', $result);

    if (0 !== $result) {
        throw new Exception('adb screencap failed');
    }

    system('adb pull /sdcard/screen.png ./screen', $result);

    if (0 !== $result) {
        throw new Exception('adb pull failed');
    }

    ob_end_clean();
}

function press($startPoint, $endPoint)
{
    $pressPointX = rand(830, 1030);
    $pressPointY = rand(1165, 1365);

    $x1 = (int)$startPoint['x'];
    $y1 = (int)$startPoint['y'];
    $x2 = (int)$endPoint['x'];
    $y2 = (int)$endPoint['y'];

    $distance = sqrt(pow($x2 - $x1, 2) + pow($y2 - $y1, 2));

    $ratio = 1.333;

    $time = (int)bcmul($distance, $ratio);

    error_log("distance：{$distance} ratio: {$ratio} time: {$time}" . PHP_EOL, 3, 'jump.log');

    ob_start();

    system(sprintf('adb shell input swipe %s %s %s %s %s', $pressPointX, $pressPointY, $pressPointX, $pressPointY, $time), $result);

    ob_end_clean();

    return $result;
}

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>WeChatJump</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .container {
            position: relative;
            width: <?=$width?>px;
            height: <?=$height?>px;
            background-color: #ccc;
            background-repeat: no-repeat;
        }

        .start, .end {
            position: absolute;
            top: 0;
            left: 0;
            border-radius: 50%;
            background: #f00;
            color: #fff;
            font-size: 14px;
            text-align: center;
        }

        .end {
            background: #000;
        }

        .hide {
            visibility: hidden;
        }

        .toolbar {
            padding: 10px 0;
        }
    </style>
</head>
<body>
<div class="toolbar">
    <button id="refresh">刷新</button>
</div>
<div class="container">
    <div class="start hide">1</div>
    <div class="end hide">2</div>
</div>

<script src="jquery.min.js"></script>
<script>
    $(function () {
        var pointWidth = 20;
        var nextCycle = false;
        var $container = $('.container');
        var $start = $container.find('.start');
        var $end = $container.find('.end');
        var startPoint = null;
        var endPoint = null;

        $start.width(pointWidth);
        $start.height(pointWidth);
        $end.width(pointWidth);
        $end.height(pointWidth);

        refreshImage();

        $('#refresh').on('click', function () {
            $.get('<?=$url?>', {action: 'refresh'}, function (response) {
                if (response.status === 1) {
                    refreshImage();
                }
            }, 'json');
        });

        $container.on('click', function (event) {
            var containerOffset = $container.offset();
            var x = event.pageX - containerOffset.left;
            var y = event.pageY - containerOffset.top;
            var point = getPoint(x, y);

            if (haveItem($start)) {
                if (haveItem($end)) {
                    if (!nextCycle) {
                        return false;
                    }
                    clearPoint();
                    addStart(point);
                } else {
                    addEnd(point);
                    $.get('<?=$url?>', {
                        action: 'jump',
                        start: getPointReal(startPoint.x, startPoint.y),
                        end: getPointReal(endPoint.x, endPoint.y)
                    }, function (response) {
                        if (response.status === 1) {
                            refreshImage();
                            clearPoint();
                            nextCycle = true;
                        }
                    }, 'json');
                }
            } else {
                addStart(point);
            }
        });

        function haveItem(item) {
            return !item.hasClass('hide');
        }

        function getPoint(x, y) {
            var radius = pointWidth / 2;
            return {x: x - radius, y: y - radius};
        }

        function getPointReal(x, y) {
            var radius = pointWidth / 2;
            return {x: x + radius, y: y + radius};
        }

        function addStart(point) {
            startPoint = point;
            $start.css('top', point.y)
                .css('left', point.x)
                .removeClass('hide');
        }

        function addEnd(point) {
            endPoint = point;
            $end.css('top', point.y)
                .css('left', point.x)
                .removeClass('hide');
        }

        function clearPoint() {
            startPoint = null;
            endPoint = null;
            $start.addClass('hide');
            $end.addClass('hide');
        }

        function refreshImage() {
            var image = 'url(screen/screen.png?' + Math.random() + ')';
            $container.css('background-image', image);
        }
    });
</script>
</body>
</html>